package com.kehao.leetcode.middle.design;

import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

public class RandomizedSet {

    private HashMap<Integer,Integer> map;
    private ArrayList<Integer> list;
    private Random random = new Random(System.currentTimeMillis());
    /** Initialize your data structure here. */
    public RandomizedSet() {
        map = new HashMap<>();
        list = new ArrayList<>();
    }

    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    public boolean insert(int val) {
        if(map.containsKey(val)) return false;
        map.put(val,list.size());
        list.add(val);
        return true;
    }

    /** Removes a value from the set. Returns true if the set contained the specified element. */
    public boolean remove(int val) {
        if(map.containsKey(val)){
            Integer index = map.get(val);
            int value = list.get(list.size()-1);
            list.set(index,value);
            list.remove(list.size()-1);
            map.put(value,index);
            map.remove(val);
            return true;
        }else {
            return false;
        }
    }

    /** Get a random element from the set. */
    public int getRandom() {
        int index = random.nextInt(list.size());
        return list.get(index);
    }


    @Test
    public void test01(){
//        ["RandomizedSet","insert","insert","remove","insert","remove","getRandom"]
//        [[],[0],[1],[0],[2],[1],[]]

        RandomizedSet randomizedSet = new RandomizedSet();
        boolean insert = randomizedSet.insert(0);
        boolean insert1 = randomizedSet.insert(1);
        boolean remove = randomizedSet.remove(0);
        boolean insert2 = randomizedSet.insert(2);
        boolean remove1 = randomizedSet.remove(1);
        int random = randomizedSet.getRandom();
    }


    @Test
    public void test02(){
//["RandomizedSet","remove","remove","insert","getRandom","remove","insert"]
//[[],[0],[0],[0],[],[0],[0]]
        RandomizedSet randomizedSet = new RandomizedSet();
        boolean remove = randomizedSet.remove(0);
        boolean remove1 = randomizedSet.remove(0);
        boolean insert = randomizedSet.insert(0);
        int random = randomizedSet.getRandom();
        boolean remove2 = randomizedSet.remove(0);
        boolean insert1 = randomizedSet.insert(0);

    }
}
